var uid = 1;
var mid = -1;
var limit = 15;
var countdown = 60; //计时60s
var countTimer;
layui.use(['table', 'form', 'laydate'], function() {
	var table = layui.table,
		$ = layui.jquery,
		layer = layui.layer,
		form = layui.form,
		laydate = layui.laydate;

	//复选框样式
	ckBoxColor();
	//初始化查询参数
	var options = {
		offset: 0,
		limit: limit,
		pageIndex: 1,
	};
	var userOptions = {
		offset: 0,
		limit: limit,
		pageIndex: 1
	};
	var tempOptions = options;
	loadData(options);
	//初始化弹窗中的下拉框
	initPID();
	$(document).keyup(function(event){
		if(event.keyCode ==13){
			$(".searchTools .search-btn").trigger("click");
		}
	});
	/**搜索按钮**/
	$(".searchTools .search-btn").on("click", function() {
		var type = $.trim($(".searchTools .type").val());
		var name = $.trim($(".searchTools .name").val());
		var datas = {
			offset: 0,
			limit: limit,
			pageIndex: 1
		};
		if(!isNull(type) && type != -1)
			datas['type'] = parseInt(type);
		if(!isNull(name))
			datas['name'] = name;
		tempOptions = datas;
		loadData(datas);
	});

	//点击禁用
	$(".menuList").on("click", ".del-btn", function() {
		var id = parseInt($(this).attr("data-id"));
		//询问框
		layer.confirm('确定要禁用吗？', {
			icon: 3,
			btn: ['确定', '取消'] //按钮
		}, function() {
			var loading = layer.load(1);
			$.ajax({
				type: "PUT",
				url: "/sys_menu/delete/" + id,
				async: true,
				dataType: 'json',
				timeout: 5000,
				data: {
					id: id
				},
				success: function(res) {
					layer.close(loading);
					// console.log(res);
					if(res.code == 0) {
						layer.msg(res.msg);
						loadData(tempOptions);
					} else {
						layer.msg(res.msg);
						return;
					}
				},
				error: function(res) {
					layer.msg("请求失败，请稍后再试！");
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时，请稍后再试！");
						layer.close(loading);
						return;
					}

				}
			});
		}, function() {
			return;
		});
	});

	//点击启用
	$(".menuList").on("click", ".on-btn", function() {
		var id = parseInt($(this).attr("data-id"));
		//询问框
		layer.confirm('确定要启用吗？', {
			icon: 3,
			btn: ['确定', '取消'] //按钮
		}, function() {
			var loading = layer.load(1);
			$.ajax({
				type: "PUT",
				url: "/sys_menu/enabled/" + id,
				async: true,
				dataType: 'json',
				timeout: 5000,
				data: {
					id: id
				},
				success: function(res) {
					layer.close(loading);
					// console.log(res);
					if(res.code == 0) {
						layer.msg(res.msg);
						loadData(tempOptions);
					} else {
						layer.msg(res.msg);
						return;
					}
				},
				error: function(res) {
					layer.msg("请求失败，请稍后再试！");
					layer.close(loading);
					return;
				},
				complete: function(XMLHttpRequest, status) {
					if(status == 'timeout') {
						layer.msg("请求超时，请稍后再试！");
						layer.close(loading);
						return;
					}

				}
			});
		}, function() {
			return;
		});
	})

	//点击添加
	$(".searchTools .add-btn").on("click", function() {
		$(".addModal").show();
				// initPID(); //初始化父级菜单
	})
	$(".addModal .close").on("click", function() {
		$(".addModal").hide();
		$(".addModal input").val("");
		$(".addModal select").val("");
		$(".addModal textarea").val("");
		form.render();
	})
	//点击添加提交
	form.on('submit(addBtns)', function() {
		var pid = $.trim($(".addModal .pid").val());
		var name = $.trim($(".addModal .name").val());
		var status = $.trim($(".addModal .status").val());
		var type = $.trim($(".addModal .type").val());
		var url = $.trim($(".addModal .url").val());
		var sortby = $.trim($(".addModal .sortby").val());
		var remark = $.trim($(".addModal .remark").val());

		if(isNull(name)) {
			layer.msg("请输入菜单名称！");
			return;
		}
		if (isNull(pid))
			pid = -1;
		var options = {
			name: name,
			pid: parseInt(pid),
			status: status,
			type: type,
			url: url,
			sortby: sortby,
			type: type
		};
		if(!isNull(remark)) {
			options['remark'] = remark;
		}
		//		console.log(options);
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: "/sys_menu/save",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					$(".addModal").hide();
					$(".addModal input").val("");
					$(".addModal select").val("");
					$(".addModal textarea").val("");
					form.render();
					loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	})
	//修改按钮
	$(".menuList").on("click", ".set-btn", function() {
		$(".updateModal").show();
		mid = $(this).attr('data-id');
		$(".updateModal .pid").val($(this).attr("data-pid"));
		$(".updateModal .name").val($(this).attr('data-name'));
		$(".updateModal .type").val($(this).attr("data-type"));
		$(".updateModal .url").val($(this).attr('data-url'));
		$(".updateModal .remark").val($(this).attr('data-remark'));
		$(".updateModal .sortby").val($(this).attr('data-sortby'));
		// $(".updateModal .status").val($(this).attr("data-status"));
		form.render();
	})
	$(".updateModal .close").on("click", function() {
		$(".updateModal").hide();
		$(".updateModal input").val("");
		$(".updateModal select").val("");
		$(".updateModal textarea").val("");
		form.render();
		$("body .ckBox").removeClass("on");
	})
	//菜单修改
	form.on('submit(updateBtns)', function() {
		var pid = $.trim($(".updateModal .pid").val());
		var name = $.trim($(".updateModal .name").val());
		var status = $.trim($(".updateModal .status").val());
		var type = $.trim($(".updateModal .type").val());
		var url = $.trim($(".updateModal .url").val());
		var remark = $.trim($(".updateModal .remark").val());
		var sortby = $.trim($(".updateModal .sortby").val());
		if(name == '' || name == null || name == undefined) {
			layer.msg("请输入菜单名称！");
			return;
		}

		var options = {
			id: mid,
			name: name,
			pid: parseInt(pid),
			status: status,
		};
		if(!isNull(remark))
			options['remark'] = remark;

		if(!isNull(url))
			options['url'] = url;

		if(!isNull(type))
			options['type'] = type;

		if(!isNull(sortby))
			options['sortby'] = sortby;

		updateMenu(options, "/sys_menu/update/" + parseInt(mid), 1);
	});

	//点击关联按钮
	$(".searchTools .user-concat-btn").on("click", function() {
		var ck = $(".tableList .ckBox.on");
		if(ck.length <= 0) {
			layer.msg("至少选择一个菜单！");
			return;
		}
		var text = $(ck[0]).attr("data-name");
		$(".userModal").show();
		$(".userModal .user-title-msg").html(text + "==>关联按钮");
		mid = parseInt($(ck[0]).attr("data-id"));
		/**加载用户信息**/
		loadUser(userOptions);
	});

	//关联按钮
	$(".userModal").on("click", ".concat-btn", function() {
		mid = parseInt($(this).attr("data-mid"));
		uid = parseInt($(this).attr('data-uid'));
		$(".concatModal").show();
		var options = {mid: parseInt(mid), uid: parseInt(uid)};
		loadButton(options);
	});

	/**关闭关联按钮弹出框**/
	$(".concatModal .close").on("click", function() {
		$(".concatModal").hide();
		$("body .ckBox").removeClass("on");
	});

	/**关闭关联按钮弹出框**/
	$(".userModal .close").on("click", function() {
		$(".userModal").hide();
		$("body .ckBox").removeClass("on");
	});

	//删除关联
	$(".concatModal").on("click", ".btn-delConcat", function() {
		var mid = $(this).attr("data-mid");
		var uid = $(this).attr('data-uid');
		var bid = $(this).attr('data-bid');
		var options = {mid: parseInt(mid), bid: parseInt(bid), uid: parseInt(uid)};
		var url = '/sys_menu/delete/relation/' + uid;
		// console.log(options)
		updateMenu(options, url, 0);
	});

	//添加关联
	$(".concatModal").on("click", ".btn-addConcat", function() {
		var mid = $(this).attr("data-mid");
		var uid = $(this).attr('data-uid');
		var bid = $(this).attr('data-bid');
		var options = {mid: parseInt(mid), bid: parseInt(bid), uid: parseInt(uid)};
		var url = '/sys_menu/add/relation/' + uid;
		// console.log(options)
		updateMenu(options, url, 0);
	});

	//获取数据列表
	function loadData(options) {
		// console.log(options)
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/sys_menu/list",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
								// console.log(res);
				if(res.code == 0) {
					$(".menuListPage").page({
						total: res.data.total, //总条数
						pageIndex: options.pageIndex, //当前页
						pageSize: options.limit, //每页显示
						showInfo: true, //是否显示记录信息
						prevBtnText: '上一页',
						nextBtnText: "下一页",
						infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
					}).on("pageClicked", function(event, pageIndex) {
						//分页点击
						options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
						options.pageIndex = pageIndex;
						loadData(options);
					});

					//具体数据列表
					var data = res.data.records;
					if(data == null || data.length <= 0) {
						$(".menuList .tableList").empty().append("<tr><td colspan='9'>暂无数据</td></tr>");
						return;
					}
					var html = '';
					$.each(data, function(index, val) {
						var statusStr = val.status == 0 ? '正常' : '禁用';
						var typeStr = '手机菜单';
						if (val.type == 0)
							typeStr = '手机菜单';
						else if (val.type == 1)
							typeStr = '后台菜单';
						else if (val.type == 2)
							typeStr = '请求URL';
						else if (val.type == 3)
							typeStr = 'OA后台菜单';
						else if (val.type == 4)
							typeStr = 'OA手机菜单';
						else if (val.type == 5)
							typeStr = 'ERP菜单';

						var statusBtn,btn = '';
						if (val.status == 0)
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn del-btn" style="background-color:#d9534f"><img src="/static/console/img/off.png" />禁用</a>';
						else
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn on-btn" style="background-color:#5FB878"><img src="/static/console/img/on.png" />启用</a>';

						btn = '<a href="javascript:void(0)" data-type="' + val.type + '" data-remark="' + val.remark + '" data-sortby="'
							+ val.sortby + '" data-url="' + val.url + '" data-id="' + val.id + '" data-pid="' + val.pid + '" data-name="'
							+ val.name + '" class="layui-btn set-btn" style="background-color:#5d6f97"><img src="/static/console/img/edit.png" />修改</a>' + statusBtn;
						html += "<tr><td>" + val.id + "</td><td>" + val.name + "</td>" +
							"<td data-type='" + val.type + "'>" + typeStr + "</td><td>" + val.pid + "</td><td>"
							+ convertVal(val.url) + "</td><td data-status='" + val.status + "'>" + statusStr + "</td><td>"
							+ convertVal(val.sortby) + "</td><td>" + convertVal(val.remark) + "</td><td>" + btn + "</td></tr>";
					});
					$(".menuList .tableList").empty().append(html);
					replaceNull($(".menuList .tableList"));
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});

	}
	//获取父级资源
	function initPID() {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: "/sys_menu/list",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: {
				limit: 1000,
				pageIndex: 1,
				offset: 0
			},
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					var datas = res.data.records;
					var html = "<option value='-1'></option>";
					$.each(datas, function(i, v) {
						var type = '手机';
						if (v.type == 0)
							type = '手机';
						else if (v.type == 1)
							type = '后台';
						else if (v.type == 2)
							type = 'URL';
						else if (v.type == 3)
							type = 'OA后台';
						else if (v.type == 4)
							type = 'OA手机';
						else if (v.type == 5)
							type = 'ERP后台';

						html += "<option value=" + v.id + ">" + v.name + "(" + type + ")</option>";
					})
					$(".msgBox .pid").empty().append(html);
					form.render();
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**加载按钮信息**/
	function loadButton(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: '/sys_menu/query/button',
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					// console.log(res.data)
					loadButtonData(res.data);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**组装按钮HTML**/
	function loadButtonData(data) {
		if(data == null || data.length <= 0) {
			$(".concatModal .menuAndButtonList .tableList").empty().append("<tr><td colspan='4'>暂无数据</td></tr>");
			return;
		}
		var html = '';
		$.each(data, function(index, val) {
			var statusText = "";
			var btn = "";
			if (val.status == 0) {
				statusText = '已关联';
				btn = "<a href='javascript:void(0)' data-uid='" + uid + "' data-mid='" + mid + "' data-bid='" + val.id + "' class='layui-btn btn-delConcat'>删除关联</a>";
			} else {
				btn = "<a href='javascript:void(0)' data-uid='" + uid + "' data-mid='" + mid + "' data-bid='" + val.id + "' class='layui-btn btn-addConcat'>添加关联</a>";
			}
			html += "<tr><td><span class='ckBox' data-id='" + val.id + "'></span></td><td>" + val.name +
				"</td><td>" + statusText + "</td><td>" + btn + "</td></tr>";
		});
		$(".concatModal .menuAndButtonList .tableList").empty().append(html);
		replaceNull($(".concatModal .menuAndButtonList .tableList"));
	}

	/**更新菜单信息**/
	function updateMenu(options, url, type) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					$(".updateModal").hide();
					$(".updateModal input").val("");
					$(".updateModal select").val("");
					$(".updateModal textarea").val("");
					form.render();
					if (type == 1)
						loadData(tempOptions);
					else if (type == 0)
						loadButton(options);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	//获取用户列表
	function loadUser(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/sys_user/list",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					$(".userListPage").page({
						total: res.data.total, //总条数
						pageIndex: options.pageIndex, //当前页
						pageSize: options.limit, //每页显示
						showInfo: true, //是否显示记录信息
						prevBtnText: '上一页',
						nextBtnText: "下一页",
						infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
					}).on("pageClicked", function(event, pageIndex) {
						//分页点击
						options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
						options.pageIndex = pageIndex;
						loadData(options);
					});

					//具体数据列表
					var data = res.data.records;
					if(data == null || data.length <= 0) {
						$(".userList .userTableList").empty().append("<tr><td colspan='4'>暂无数据</td></tr>");
						return;
					}
					var html = '';
					$.each(data, function(index, val) {
						var typeStr = '普通用户';
						var btn = '<a href="javascript:void(0)" data-uid="' + val.id + '" data-mid="' + mid + '" class="layui-btn concat-btn" style="background-color:#61C3A2"><img src="/static/console/img/concat.png" />关联按钮</a>';
						if (val.type == 1)
							typeStr = '系统用户';
						else
							typeStr = '普通用户';


						html += "<tr><td>" + val.username + "</td><td>" + val.name + "</td><td>" + typeStr +
							"</td><td>" + btn + "</td></tr>";
					});
					$(".userList .userTableList").empty().append(html);
					replaceNull($(".userList .userTableList"));
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});

	}

	/**显示值转换**/
	function convertVal(val) {
		if (val == null || val == '' || val == undefined)
			return '';
		else
			return val;
	}
	
});